package evi.com.evi.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.picasso.Picasso;

import java.io.IOException;

import evi.com.evi.R;
import evi.com.evi.application.MyApplication;
import evi.com.evi.utils.AppUtils;
import evi.com.evi.utils.CircleTransform;
import evi.com.evi.utils.ConnectUtil;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.PopTime;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ScreenUtils;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 用户信息
 *
 * @author MY
 */
public class UserInfoActivity extends Activity implements OnClickListener {

    private static final String TAG = "TAG";
    private ImageView iv_shop_icon;   //商家图片
    private TextView tv_shop_name;    //商家名字

    private ImageView tv_return_back;

    private RelativeLayout rl_01;
    private RelativeLayout rl_02;
    private RelativeLayout rl_03;
    private RelativeLayout rl_04;

    private TextView content1;      //地址
    private TextView content2;      //电话
    private TextView content3;      //公告
    private TextView content4;      //开始时间
    private TextView content4_2;    //结束时间

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    private Dialog dialog;

    private String imageUrl;
    private String name;
    private String address;
    private String phoneNo;
    private String announcement;
    private String startTime;
    private String stopTime;

    private Intent intent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ScreenUtils.setTranStatus(this, false, Color.parseColor("#FC9E61"));
        MyApplication.getInstance().addActivity(this);
        setContentView(R.layout.activity_user_info);
        initView();
    }

    private void initView() {
        tv_return_back = (ImageView) findViewById(R.id.tv_return_back);
        tv_return_back.setOnClickListener(this);

        iv_shop_icon = (ImageView) findViewById(R.id.iv_shop_icon);
        tv_shop_name = (TextView) findViewById(R.id.tv_shop_name);
        rl_01 = (RelativeLayout) findViewById(R.id.rl_01);
        rl_02 = (RelativeLayout) findViewById(R.id.rl_02);
        rl_03 = (RelativeLayout) findViewById(R.id.rl_03);
        rl_04 = (RelativeLayout) findViewById(R.id.rl_04);

        content1 = (TextView) findViewById(R.id.content1);
        content2 = (TextView) findViewById(R.id.content2);
        content3 = (TextView) findViewById(R.id.content3);
        content4 = (TextView) findViewById(R.id.content4);
        content4_2 = (TextView) findViewById(R.id.content4_2);

        iv_shop_icon.setOnClickListener(this);
        rl_01.setOnClickListener(this);
        rl_02.setOnClickListener(this);
        rl_03.setOnClickListener(this);
        content4.setOnClickListener(this);
        content4_2.setOnClickListener(this);

        client = new OkHttpClient();
        jsonUtils = new JSONUtils();

        getInfo();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        getInfo();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_return_back:
                finish();
                break;

            case R.id.iv_shop_icon:        //头像
                intent = new Intent(UserInfoActivity.this, HeaderChangeActivity.class);
                startActivityForResult(intent, 0);
                break;

            case R.id.rl_01:        //地址
                intent = new Intent(UserInfoActivity.this, AddressActivity.class);
                intent.putExtra("content", address);
                startActivityForResult(intent, 1);
                break;

            case R.id.rl_02:        //电话
                intent = new Intent(UserInfoActivity.this, TelephoneActivity.class);
                intent.putExtra("content", phoneNo);
                startActivityForResult(intent, 2);
                break;

            case R.id.rl_03:        //公告
                intent = new Intent(UserInfoActivity.this, NoticeActivity.class);
                intent.putExtra("content", announcement);
                startActivityForResult(intent, 3);
                break;

            case R.id.content4:        //开始时间
                new PopTime().showFullScreen(UserInfoActivity.this, "时间选择",
                        new PopTime.DateBack() {
                            @Override
                            public void sure(String date) {
                                content4.setText(date);
                                startTime = date;
                            }
                        });
                break;

            case R.id.content4_2:        //结束时间
                new PopTime().showFullScreen(UserInfoActivity.this, "时间选择",
                        new PopTime.DateBack() {
                            @Override
                            public void sure(String date) {
                                content4_2.setText(date);
                                stopTime = date;
                                updateInfo();
                            }
                        });
                break;

            default:
                break;
        }
    }

    //上传时间
    private void updateInfo() {
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在上传");
        dialog.show();
//        String phoneNo = et_input.getText().toString();

        String token = SPUtil.getString(this, "token");
        startTime = startTime.replace(":", "");
        stopTime = stopTime.replace(":", "");

        FormBody.Builder builder = new FormBody.Builder();
        builder.add("startTime", startTime + "00");
        builder.add("stopTime", stopTime + "00");

        RequestBody body = builder.build();


        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.updateMerchant_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(UserInfoActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        toast("修改成功");
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
                Log.e(TAG, "更新商家联网成功" + jsonData);
            }
        });
    }


    //获取商家信息
    private void getInfo() {
        //getMerchantInfo_url
        dialog = AppUtils.getLoadingDialog(this, "提示", "正在连接服务器，请稍后");
        dialog.show();
        String token = SPUtil.getString(this, "token");

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtils.getMerchantInfo_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                toast("网络信号不佳，加载失败");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(ConnectUtil.isConnect(UserInfoActivity.this)){
                            toast("网络信号不佳，加载失败");
                        } else {
                            toast("网络未联接，请检查");
                        }
                    }
                });
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtils.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        imageUrl = jsonObject.getJSONObject("data").getString("imageUrl");
                        name = jsonObject.getJSONObject("data").getString("name");
                        address = jsonObject.getJSONObject("data").getString("address");
                        phoneNo = jsonObject.getJSONObject("data").getString("phoneNo");
                        announcement = jsonObject.getJSONObject("data").getString("announcement");
                        startTime = jsonObject.getJSONObject("data").getString("startTime");
                        stopTime = jsonObject.getJSONObject("data").getString("stopTime");

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Picasso.with(UserInfoActivity.this).load(imageUrl).transform(new CircleTransform()).into(iv_shop_icon);
                                tv_shop_name.setText(name);
                                content1.setText(address);
                                content2.setText(phoneNo);
                                content3.setText(announcement);
                                if (startTime != null) {
                                    if (startTime.length() == 5) {
                                        content4.setText(startTime.substring(0, 1) + ":" + startTime.substring(1, 3));
                                    } else if (startTime.length() == 6) {
                                        content4.setText(startTime.substring(0, 2) + ":" + startTime.substring(2, 4));
                                    }
                                }
                                if (stopTime != null) {
                                    if (stopTime.length() == 5) {
                                        content4_2.setText(stopTime.substring(0, 1) + ":" + stopTime.substring(1, 3));
                                    } else if (stopTime.length() == 6) {
                                        content4_2.setText(stopTime.substring(0, 2) + ":" + stopTime.substring(2, 4));
                                    }
                                }
                                dialog.dismiss();
                            }
                        });
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }
        });
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(UserInfoActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.getInstance().deleteActivity(this);
    }
}